package com.itboye.jinpuyiyuan.activity.home.testserver;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.activity.pay.PayActivity;
import com.itboye.jinpuyiyuan.adapter.ReportAdapter;
import com.itboye.jinpuyiyuan.adapter.ShopCartAdapter;
import com.itboye.jinpuyiyuan.adapter.TestServerFixedAdapter;
import com.itboye.jinpuyiyuan.adapter.TestServerOptionLeftAdapter;
import com.itboye.jinpuyiyuan.adapter.TestServerOptionRightAdapter;
import com.itboye.jinpuyiyuan.adapter.TestServerOrderAdapter;
import com.itboye.jinpuyiyuan.adapter.TestServerPayGridAdapter;
import com.itboye.jinpuyiyuan.base.BaseActivity;
import com.itboye.jinpuyiyuan.bean.AppointPhysicalBean;
import com.itboye.jinpuyiyuan.bean.OptionMenuBean;
import com.itboye.jinpuyiyuan.bean.PhyAppointBean;
import com.itboye.jinpuyiyuan.bean.PhysicalListBean;
import com.itboye.jinpuyiyuan.bean.SelfPhysicalsBean;
import com.itboye.jinpuyiyuan.bean.TestServerOrder;
import com.itboye.jinpuyiyuan.interfaces.IGoodsCardRA;
import com.itboye.jinpuyiyuan.interfaces.IRecordGoodsCart;
import com.itboye.jinpuyiyuan.presenter.BranchAddressPresenter;
import com.itboye.jinpuyiyuan.utils.YuYueChooseTimePopwindow;
import com.itboye.jinpuyiyuan.utils.download_pdf.DownloadService;
import com.itboye.jinpuyiyuan.utils.sputil.Const;
import com.itboye.jinpuyiyuan.utils.sputil.SPUtils;
import com.itboye.jinpuyiyuan.utils.volley.ResultEntity;
import com.itboye.jinpuyiyuan.widget.LimitListView;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;


import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.FileCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;


/**
 * Created by Administrator on 2017/12/11 0011.
 */

public class TestServerActivity extends BaseActivity implements  Observer, IRecordGoodsCart, IGoodsCardRA, YuYueChooseTimePopwindow.onFinishedLisenter, ReportAdapter.OnItemClickListen {
    //title
    private ImageView leftImg,rightImg;
    private TextView leftTv,tvTitle;
    private RelativeLayout rlLeft,toobar;

    private BranchAddressPresenter presenter;
    private String uid;
    //预约的界面ui
    private RelativeLayout testTablePayRL;
    private TextView testTablePayTv,testTablePresentationTv;
//            testTableOrderTv;
    private ImageView moveLine;
    private LinearLayout testServerOrderLL,testServerPayLL,testServerPresentLL;
    private ListView testOrderList;
    private TestServerOrderAdapter testServerOrderAdapter;
    private ArrayList<TestServerOrder> list;
    //moveline
    private int moveDistance;//移动的距离
    private int moveLineWidth;
    private int currIndex;

   //购买的界面ui
    private GridView testServerPayGv;
    private LinearLayout testServerTableLL;//有全部的table
    private TextView testServerPayAllTv,testServerPayTable1,testServerPayMoreTV;
    private ListView testServerPayFixedList;//固定体检套餐list
    private LinearLayout testServerPayOptionLL;//包含自选list的ll，控制显示

    private ListView testServerPayOptionLeftList,testServerPayOptionRightList;//自选体检套餐list
    private TextView testServerPayFixedTv,testServerPayOptionTv;//固定体检套餐和自选体检套餐



    private TestServerPayGridAdapter testServerPayGridAdapter;
    private ArrayList<String> gridList;
    private ArrayList<String> tableList;//table显示的list

    private RelativeLayout paygoodsRl;//购买的layout
    private TextView confirmPayTv;//确认购买按钮
    private RelativeLayout goodsCartList;//购物车 购物列表
    private RelativeLayout shopcartRl;//包含的购物车图片
    private ImageView payGoodsImg;
    private TextView payManeyTv,goodsNumTv;

    private ArrayList<PhysicalListBean.PhysicalBean> fixedList;//固定体检套餐的list
    private TestServerFixedAdapter fixedAdapter;//固定体检套餐的adapter
    private LimitListView goodCartNumLv;//购物list

    private TextView deleteALlTv;//清除所有tv
    private ImageView deleteAllImg;//清除所有图片




    //自选套餐选择的items
    private ArrayList<OptionMenuBean.Depts.Items> rightSelects; //选中的套餐
    private String deptId;//记录当前的left选中的item position
    private Map<String,ArrayList<OptionMenuBean.Depts.Items>> map; //记录right 选择的item

    private ArrayList<SelfPhysicalsBean.DeptBean> optionLeftList;//自选体检套餐left的list
    private ArrayList<OptionMenuBean.Depts.Items> rightList;//自选体检套餐right的list
    private TestServerOptionLeftAdapter leftAdapter;
    private TestServerOptionRightAdapter rightAdapter;
    private ShopCartAdapter shopCartAdapter;

    //固定体检套餐刷新
    private SmartRefreshLayout refresh;
    private int page=1;
    private int pagesize=10;
    private boolean isRefresh=true;

    //报告
    private  SmartRefreshLayout reportRefresh;
    private RecyclerView reportLv;
    private ReportAdapter mReportAdapter;
    private  List<PhyAppointBean.CheckUp> checkUps;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_testserver);
        uid= SPUtils.get(this,null, Const.UID,"")+"";
        map=new HashMap<>();
        goodsNumTv.setVisibility(View.GONE);
        presenter=new BranchAddressPresenter(this);

        initTitleView();
        initPayData();
        initReport(); //报告页面 初始化

    }


    //体检报告
    private void initReport() {

        checkUps=new ArrayList<>();
        mReportAdapter=new ReportAdapter(this,checkUps,this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        reportLv.setLayoutManager(linearLayoutManager);
        reportLv.setAdapter(mReportAdapter);

        reportRefresh.setEnableLoadmore(false);
//        WaveSwipeHeader waveSwipeHeader = new WaveSwipeHeader(this);
//        waveSwipeHeader.setColorSchemeColors(getResources().getColor(R.color.colorAccent));

        reportRefresh.autoRefresh();
        reportRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                presenter.getPhyAppoint(uid);
            }
        });

        ClassicsHeader classicsHeader = new ClassicsHeader(this);
        ClassicsFooter classicsFooter = new ClassicsFooter(this);

        reportRefresh.setRefreshHeader(classicsHeader);
        reportRefresh.setRefreshFooter(classicsFooter);
    }

    //购买相关数据
    private void initPayData() {
        gridList=new ArrayList<>();
        tableList=new ArrayList<>();
        for (int i=0;i<13;i++){
         gridList.add("金色童年"+i);
         if (i==12){
             gridList.add("返回");
         }
        }
        testServerPayGridAdapter=new TestServerPayGridAdapter(this,gridList);
        testServerPayGv.setAdapter(testServerPayGridAdapter);
        testServerPayTable1.setText(gridList.get(0));
        testServerPayGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position==(gridList.size()-1)){
                }else {
                    testServerPayTable1.setText(gridList.get(position));
                    testServerPayAllTv.setTextColor(getResources().getColor(R.color.black));
                    testServerPayTable1.setTextColor(getResources().getColor(R.color.title_blue));
                }

                testServerPayGv.setVisibility(View.GONE);
                testServerTableLL.setVisibility(View.VISIBLE);


            }
        });
        //固定体检套餐数据初始化
        fixedList=new ArrayList<>();
        refresh.setEnableLoadmore(true);
//        WaveSwipeHeader waveSwipeHeader = new WaveSwipeHeader(this);
//        waveSwipeHeader.setColorSchemeColors(getResources().getColor(R.color.colorAccent));

        refresh.autoRefresh();
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
              isRefresh=true;
              page=1;
              presenter.physicalList(uid,"-1",page,pagesize);
            }
        });
        refresh.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                isRefresh=false;
                page++;
                presenter.physicalList(uid,"-1",page,pagesize);
            }
        });
        ClassicsHeader classicsHeader = new ClassicsHeader(this);
        ClassicsFooter classicsFooter = new ClassicsFooter(this);

        refresh.setRefreshHeader(classicsHeader);
        refresh.setRefreshFooter(classicsFooter);

//        presenter.physicalList(uid,"-1",page,pagesize);

        fixedAdapter=new TestServerFixedAdapter(this,fixedList);
        testServerPayFixedList.setAdapter(fixedAdapter);

        testServerPayFixedList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

//                view.findViewById(R.id.queryDetail).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
                        Intent intent = new Intent(TestServerActivity.this, TestServerFixedQueryDetailActivity.class);
                        PhysicalListBean.PhysicalBean physicalBean = fixedList.get(position);
                        intent.putExtra("item",physicalBean);
                        startActivity(intent);
//                    }
//                });


            }
        });


        //自选体检套餐数据初始化
        optionLeftList=new ArrayList<>();
        rightList=new ArrayList<>();
        rightSelects=new ArrayList<>();

        presenter.getSelfList(uid);

        leftAdapter=new TestServerOptionLeftAdapter(this,optionLeftList);
        //

        rightAdapter=new TestServerOptionRightAdapter(this,this,rightList,deptId);
        shopCartAdapter=new ShopCartAdapter(this,this,rightSelects);


        testServerPayOptionLeftList.setAdapter(leftAdapter);
        testServerPayOptionRightList.setAdapter(rightAdapter);

        goodCartNumLv.setAdapter(shopCartAdapter);
        testServerPayOptionLeftList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                leftAdapter.cancleAllItemState(position);
                //刷新右侧list数据  同时传入上次选中的item的个数
                deptId=optionLeftList.get(position).getDeptid().trim();
                //判断map 对应有没有值有点话 直接上数据
                Log.d("dept==",deptId);

                if (map.get(deptId)!=null){
                    ArrayList<OptionMenuBean.Depts.Items> items = map.get(deptId);
                    rightAdapter.addData(items,deptId);
                }else {
                    showProgressDialog("数据加载中...",false);
                    presenter.getPhysicals(uid,deptId);
                }

            }
        });
        testServerPayOptionRightList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });
    }


    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){
            case R.id.rlLeft:
            case R.id.leftImg:
                this.finish();
                break;
            //购买
            case R.id.testTablePayRL:
            case R.id.testTablePayTv:
                cancleTableState() ;
                testServerPayLL.setVisibility(View.VISIBLE);

                tranSlate(0,300);
                testTablePayTv.setTextColor(getResources().getColor(R.color.title_blue));
                currIndex=0;

                if (testServerPayFixedList.getVisibility()==View.VISIBLE){
                    paygoodsRl.setVisibility(View.GONE);
                }else {
                    paygoodsRl.setVisibility(View.VISIBLE);
                }
                break;
                //预约
//            case R.id.testTableOrderTv:
//                cancleTableState() ;
//                testServerOrderLL.setVisibility(View.VISIBLE);
//                tranSlate(0,300);
////                testTableOrderTv.setTextColor(getResources().getColor(R.color.title_blue));
//                currIndex=0;
//                break;

                //报告
            case R.id.testTablePresentationTv:
                cancleTableState() ;
                testServerPresentLL.setVisibility(View.VISIBLE);
                tranSlate(1,300);
                testTablePresentationTv.setTextColor(getResources().getColor(R.color.title_blue));
                currIndex=1;
                paygoodsRl.setVisibility(View.GONE);
                showProgressDialog("数据加载中...",false);
                presenter.getPhyAppoint(uid);
                break;

            //购买界面
            //全部
            case R.id.testServerPayAllTv:
                testServerPayTable1.setTextColor(getResources().getColor(R.color.black));
                testServerPayAllTv.setTextColor(getResources().getColor(R.color.title_blue));

                break;
            // 更多
            case R.id.testServerPayMoreTV:
                testServerTableLL.setVisibility(View.GONE);
                testServerPayGv.setVisibility(View.VISIBLE);
                break;

            //固定体检套餐
            case R.id.testServerPayFixedTv:
                canclePayState();
                testServerPayFixedList.setVisibility(View.VISIBLE);
                testServerPayFixedTv.setTextColor(getResources().getColor(R.color.title_blue));
                showProgressDialog("数据加载中...",false);
                presenter.physicalList(uid,"-1",page,pagesize);
                break;
            //自选体检套餐
            case R.id.testServerPayOptionTv:
                canclePayState();
                testServerPayOptionLL.setVisibility(View.VISIBLE);
                testServerPayOptionTv.setTextColor(getResources().getColor(R.color.title_blue));

                paygoodsRl.setVisibility(View.VISIBLE);

                break;
            case R.id.shopcartRl:
            case R.id.payGoodsImg:
            case R.id.goodsNumTv:
                if (rightSelects.size()>0){
                    if (goodsCartList.getVisibility()==View.VISIBLE){
                        goodsCartList.setVisibility(View.GONE);
                    }else {
                        goodsCartList.setVisibility(View.VISIBLE);
                    }
                }else {
                    goodsCartList.setVisibility(View.GONE);
                }
                break;

                //清空购物车
            case R.id.deleteALlImg:
            case R.id.deleteALlTv:

                for (SelfPhysicalsBean.DeptBean left:optionLeftList){
                    left.setItemSelects(0);
                    if (map.get(left.getDeptid().trim())!=null){
                        for (OptionMenuBean.Depts.Items items:map.get(left.getDeptid().trim())){
                            items.setSelects(0);
                        }
                    }
                }
                leftAdapter.notifyDataSetChanged();
                rightAdapter.notifyDataSetChanged();
                rightSelects.clear();
                shopCartAdapter.notifyDataSetChanged();
                goodsNumTv.setText(0+"");
                goodsNumTv.setVisibility(View.GONE);
                goodsCartList.setVisibility(View.GONE);
                payManeyTv.setText("");
                break;

            case R.id.confirmPayTv:
                showTimePop(view);
                break;

        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        moveDistance = testTablePayRL.getMeasuredWidth();
        moveLineWidth=testTablePayTv.getMeasuredWidth();
        RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(moveLineWidth,4);

        params.addRule(RelativeLayout.ALIGN_BOTTOM,R.id.TableLL);
        params.leftMargin=(moveDistance-moveLineWidth)/2;
        moveLine.setLayoutParams(params);

        Log.d("==========",moveDistance+"");
    }

    private void initTitleView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.title_blue));
        }
        leftTv.setVisibility(View.GONE);
        rightImg.setVisibility(View.GONE);
        tvTitle.setText("体检服务");

        //预约相关数据
        testTablePayTv.setTextColor(getResources().getColor(R.color.title_blue));
        currIndex = 0;
//        testTableOrderTv.setTextColor(getResources().getColor(R.color.title_blue));

        //预约相关数据
//        testTableOrderTv.setTextColor(getResources().getColor(R.color.title_blue));
//        currIndex = 0;
//        testTableOrderTv.setTextColor(getResources().getColor(R.color.title_blue));
        list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {

            TestServerOrder testServerOrder = new TestServerOrder();
            testServerOrder.setOrderDate("2017.12.6");
            testServerOrder.setOrderPersonNum(40);
            testServerOrder.setOrderState("不可预约");
            testServerOrder.setOrderWeekday("周三");
            list.add(testServerOrder);
        }
        testServerOrderAdapter=new TestServerOrderAdapter(this,list);
        testOrderList.setAdapter(testServerOrderAdapter);


    }
    /**
     * 平移动画
     *
     * @param currentItem
     * @param durationMillis
     */
    public void tranSlate(int currentItem, long durationMillis) {
        float one = moveDistance;
        Log.v("offest", "" + moveDistance);

        Animation animation = new TranslateAnimation(currIndex * one,
                currentItem * one, 0, 0);// 平移动画
        Log.v("currentoffest", "" + currIndex * one);
        Log.v("currentItem", "" + currentItem * one);
        animation.setFillAfter(true);// 动画终止时停留在最后一帧，不然会回到没有执行前的状态
        animation.setDuration(durationMillis);// 动画持续时间0.2秒
        moveLine.startAnimation(animation);// 是用ImageView来显示动画的
    }

    //购买 预约 报告
    public void cancleTableState(){
        testTablePayTv.setTextColor(getResources().getColor(R.color.black));
//        testTableOrderTv.setTextColor(getResources().getColor(R.color.black));
        testTablePresentationTv.setTextColor(getResources().getColor(R.color.black));
        testServerOrderLL.setVisibility(View.GONE);
        testServerPayLL.setVisibility(View.GONE);
        testServerPresentLL.setVisibility(View.GONE);
    }
    //固定体检套餐和自选体检套餐

    public void canclePayState(){
        testServerPayFixedTv.setTextColor(getResources().getColor(R.color.black));
        testServerPayOptionTv.setTextColor(getResources().getColor(R.color.black));

        testServerPayFixedList.setVisibility(View.GONE);
        testServerPayOptionLL.setVisibility(View.GONE);
        paygoodsRl.setVisibility(View.GONE);
    }


    String fileName;
    long doawloadId;
    @Override
    public void update(Observable o, Object arg) {

        ResultEntity entity = handlerError(arg);
        refresh.finishRefresh();
        refresh.finishLoadmore();
        reportRefresh.finishRefresh();
        if (entity.getEventType()==BranchAddressPresenter.By_Hospitalization_staticMenu_success){//获取固定体检套餐

            PhysicalListBean bean= (PhysicalListBean) entity.getData();
            if (isRefresh){
                fixedList.clear();
                fixedList.addAll(bean.getPakage_list());
            }else {
                fixedList.addAll(bean.getPakage_list());
            }
            fixedAdapter.addData(fixedList);

        }else if (entity.getEventType()==BranchAddressPresenter.By_Hospitalization_staticMenu_fail){
            MAlert.alert(entity.getMsg());
        }else if (entity.getEventType()==BranchAddressPresenter.By_Hospitalization_deptList_success){//获取自选体检套餐 left
            if (optionLeftList.size()>0){
                optionLeftList.clear();
            }
            SelfPhysicalsBean bean= (SelfPhysicalsBean) entity.getData();
            optionLeftList.addAll(bean.getDept_list());
            leftAdapter.addData(optionLeftList);
            //默认第一个数据
            if ("".equals(deptId)||null==deptId){
                deptId=optionLeftList.get(0).getDeptid().trim();
            }
            showProgressDialog("数据加载中...",false);
            presenter.getPhysicals(uid,deptId);


        }else if (entity.getEventType()==BranchAddressPresenter.By_Hospitalization_deptList_fail){

            MAlert.alert(entity.getMsg());
        }else if (entity.getEventType()==BranchAddressPresenter.By_Hospitalization_optionalMenu_success){ //获取自选体检套餐 right
            if (rightList.size()>0){
                rightList.clear();
            }
            OptionMenuBean bean= (OptionMenuBean) entity.getData();
//            ArrayList<OptionMenuBean.Depts.Items> item_list = bean.getDept_list().get(0).getItem_list();
            rightList.addAll(bean.getDept_list().get(0).getItem_list());
            rightAdapter.addData(rightList,deptId);
            map.put(deptId,bean.getDept_list().get(0).getItem_list());

        }else if (entity.getEventType()==BranchAddressPresenter.By_Hospitalization_optionalMenu_fail){
            if (rightList.size()>0){
                rightList.clear();
            }
            rightAdapter.addData(rightList,deptId);
            MAlert.alert(entity.getMsg());

        }else if (entity.getEventType()== BranchAddressPresenter.By_Hospitalization_appointment_success){ //预约体检确认

            AppointPhysicalBean bea= (AppointPhysicalBean) entity.getData();
            Intent intent = new Intent(this, PayActivity.class);
            intent.putExtra("order_id",bea.getOrder_code());
            intent.putExtra("remark",bea.getNote());
            startActivity(intent);
        }else if (entity.getEventType() ==BranchAddressPresenter.By_Hospitalization_appointment_fail){
            MAlert.alert(entity.getMsg());
        }else if (entity.getEventType() == BranchAddressPresenter.By_Hospitalization_getCheckList_success){
            if (checkUps.size()>0){
                checkUps.clear();
            }
            PhyAppointBean bean= (PhyAppointBean) entity.getData();
            checkUps.addAll(bean.getCheckup_list());
            mReportAdapter.addData(checkUps);
        }else if (entity.getEventType()==BranchAddressPresenter.By_Hospitalization_getCheckList_fail){
            MAlert.alert(entity.getMsg());
        }else if (entity.getEventType()==BranchAddressPresenter.By_Hospitalization_getReport_success){
            if (entity.getData()!=null||!entity.getData().equals("")){

//                String url= "http://api.jp.8raw.com:8087/pdf/1808150010.pdf" ;
               String url= "http://api.jp.8raw.com:8087/"+entity.getData();
                int end = url.lastIndexOf("/");
                fileName = url.substring(end + 1, url.length());
                Log.d("=====url",fileName);
                if (fileIsExists(Environment.getExternalStorageDirectory() +
                        "/temp/"+fileName)){
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    //判断是否是AndroidN以及更高的版本
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        intent.addCategory("android.intent.category.DEFAULT");
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                        Uri contentUri = FileProvider.getUriForFile(TestServerActivity.this,  "jinpuyiyuan.fileprovider", new File(Environment.getExternalStorageDirectory() +
                                "/temp/"+fileName));
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        intent.setDataAndType(contentUri, "application/pdf");
                    } else {
                        intent.addCategory("android.intent.category.DEFAULT");
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() +
                                "/temp/"+fileName));
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        intent.setDataAndType(uri, "application/pdf");
                    }

                    try {
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }else {
                    showProgressDialog("报告正在加载中...",false);
                    downPdf(url,fileName);
                }
//                initPdf("http://api.jp.8raw.com:8087/"+entity.getData());

            }
        }else if (entity.getEventType()==BranchAddressPresenter.By_Hospitalization_getReport_fail){
             MAlert.alert(entity.getMsg());
        }
        try{
            closeProgressDialog();
        }catch (Exception e){

        }
    }

    private void setFileDer(String file,String fileName) {
        File folder = new File(file);
        if (!folder.exists()) {
            folder.mkdir();//创建目录
        }
        File test_f = new File(folder, fileName);
        if (!test_f.exists()) {
            try {
                test_f.createNewFile();//创建文件
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

//        return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
    }


    @Override
    public void finish() {
        super.finish();
    }

    //right item 添加
    @Override
    public void onChange(String dept,int position,boolean isAdd) {
        //添加到map
//        map.put(dept,list);
        ArrayList<OptionMenuBean.Depts.Items> items1 = map.get(dept);
        int selects = items1.get(position).getSelects();
        if (isAdd){
            items1.get(position).setSelects(selects+1);
        }else {
            items1.get(position).setSelects(selects-1);
        }

        Log.d("dept==change",dept);
        //遍历所有的OptionMenuBean.Depts.Items 找到select 的items
        Log.d("dept==statime",System.currentTimeMillis()+"");
        if (rightSelects.size()>0){
            rightSelects.clear();
        }
        for (SelfPhysicalsBean.DeptBean deptBean:optionLeftList){
            if (map.get(deptBean.getDeptid().trim())!=null){

                for (OptionMenuBean.Depts.Items items:map.get(deptBean.getDeptid().trim())){
                    if (items.getSelects()>0){ //遍历所有套餐 添加到购物车
                        items.setDept(deptBean.getDeptid().trim());
                        rightSelects.add(items);
                    }
                }
            }
        }
        shopCartAdapter.addData(rightSelects);

        //left deptId红点 添加
        int num=0;
        int sum=0;
        for (OptionMenuBean.Depts.Items items:items1){
            num+=items.getSelects();
        }

        for (SelfPhysicalsBean.DeptBean deptBean:optionLeftList){
            sum+=deptBean.getItemSelects();
            if (dept.equals(deptBean.getDeptid().trim())){
                deptBean.setItemSelects(num);
            }
        }
        leftAdapter.addData(optionLeftList);

        if (isAdd){
            goodsNumTv.setText(sum+1+"");
        }else {
            goodsNumTv.setText(sum-1+"");
        }

        if (!goodsNumTv.getText().toString().trim().equals("0")){
            goodsNumTv.setVisibility(View.VISIBLE);
        }else {
            goodsNumTv.setVisibility(View.GONE);
        }

        getItemDatas();
        if (fee>0){
            payManeyTv.setText("￥"+fee/100);
        }else {
            payManeyTv.setText("");
        }
        fee=0;
        itemdatas="";
        Log.d("dept==time",System.currentTimeMillis()+"sum=="+sum);
    }


    @Override
    public void onGoodsChange(String deptId,String itemId,boolean isAdd) {

        ArrayList<OptionMenuBean.Depts.Items> items1 = map.get(deptId);

        for (OptionMenuBean.Depts.Items items:items1){
            if (items.getItemid().trim().equals(itemId)){
                if (isAdd){
                    items.setSelects(items.getSelects()+1);
                }else {
                    items.setSelects(items.getSelects()-1);
                }
            }
        }
        rightAdapter.notifyDataSetChanged();
        //遍历所有的OptionMenuBean.Depts.Items 找到select 的items
        Log.d("dept==statime",System.currentTimeMillis()+"");
        if (rightSelects.size()>0){
            rightSelects.clear();
        }
        for (SelfPhysicalsBean.DeptBean deptBean:optionLeftList){
            if (map.get(deptBean.getDeptid().trim())!=null){
                for (OptionMenuBean.Depts.Items items:map.get(deptBean.getDeptid().trim())){
                    if (items.getSelects()>0){ //遍历所有套餐 添加到购物车
                        rightSelects.add(items);
                    }
                }
            }
        }
        shopCartAdapter.addData(rightSelects);

        //left deptId红点 添加
        int num=0;
        int sum=0;
        for (OptionMenuBean.Depts.Items items:items1){
            num+=items.getSelects();
        }

        for (SelfPhysicalsBean.DeptBean deptBean:optionLeftList){
            sum+=deptBean.getItemSelects();
            if (deptId.equals(deptBean.getDeptid().trim())){
                deptBean.setItemSelects(num);
            }
        }
        leftAdapter.addData(optionLeftList);

        if (isAdd){
            goodsNumTv.setText(sum+1+"");
        }else {
            goodsNumTv.setText(sum-1+"");
        }

        if (!goodsNumTv.getText().toString().trim().equals("0")){
            goodsNumTv.setVisibility(View.VISIBLE);
            goodsCartList.setVisibility(View.VISIBLE);
        }else {
            goodsNumTv.setVisibility(View.GONE);
            goodsCartList.setVisibility(View.GONE);
        }

        getItemDatas();
        if (fee>0){
            payManeyTv.setText("￥"+fee/100);
        }else {
            payManeyTv.setText("");
        }
        fee=0;
        itemdatas="";

    }


    public void showTimePop(View v){
        YuYueChooseTimePopwindow chooseTimePopwindow = new YuYueChooseTimePopwindow(this,this,true);
        chooseTimePopwindow.getContentView().findViewById(R.id.time).setVisibility(View.GONE);
        chooseTimePopwindow.getContentView().findViewById(R.id.min).setVisibility(View.GONE);
        chooseTimePopwindow.showAtLocation(v, Gravity.BOTTOM
                | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    String itemdatas=""; //自选数据（多个,分开 自选的时候传）
    int fee;  //本次预约支付金额
    @Override
    public void getBeginTime(String year, String month, String day, String hour, String minite) {
//        MAlert.alert("start"+year+"-"+month+"-"+day+" "+hour+":"+minite);
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date parse = format.parse(year + "-" + month + "-" + day);
            //自选
            getItemDatas();
            presenter.physicalOrder(uid,"0","",itemdatas,fee+"",parse.getTime()/1000+"");
            fee=0;
            itemdatas="";
        } catch (ParseException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void getEndTime(String year, String month, String day, String hour, String minite) {

        MAlert.alert("end"+year+"-"+month+"-"+day+" "+hour+":"+minite);
    }

    private void getItemDatas(){
        for (OptionMenuBean.Depts.Items item:rightSelects){

            if (item.getSelects()>0){
                itemdatas+=item.getItemid()+",";
                fee+=Float.parseFloat(item.getItemprice())*100;
            }
        }

    }

    //查看报告
    @Override
    public void onItemClicks(String checkId) {
        presenter.getReporter(uid,checkId);
    }


    //判断文件是否存在
    public boolean fileIsExists(String strFile)
    {
        try
        {
            File f=new File(strFile);
            if(!f.exists())
            {
                return false;
            }

        }
        catch (Exception e)
        {
            return false;
        }

        return true;
    }

//    String pdfUrl = "http://partners.adobe.com/public/developer/en/xml/AdobeXMLFormsSamples.pdf";
    public void downPdf(String pdfUrl,String fileName) {
        OkHttpUtils.get(pdfUrl)//
                .tag(this)//
                .execute(new DownloadFileCallBack(Environment.getExternalStorageDirectory() +
                        "/temp", fileName));//保存到sd卡
    }

    private class DownloadFileCallBack extends FileCallback {

        public DownloadFileCallBack(String destFileDir, String destFileName) {
            super(destFileDir, destFileName);
        }

        @Override
        public void onBefore(BaseRequest request) {
        }

        @Override
        public void onResponse(boolean isFromCache, File file, Request request, Response response) {
//            btnFileDownload.setText("下载完成");
            closeProgressDialog();
            Intent intent = new Intent(Intent.ACTION_VIEW);
            //判断是否是AndroidN以及更高的版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addCategory("android.intent.category.DEFAULT");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                Uri contentUri = FileProvider.getUriForFile(TestServerActivity.this,  "jinpuyiyuan.fileprovider", new File(Environment.getExternalStorageDirectory() +
                        "/temp/"+fileName));
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(contentUri, "application/pdf");
            } else {
                intent.addCategory("android.intent.category.DEFAULT");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() +
                        "/temp/"+fileName));
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(uri, "application/pdf");
            }
            try{
                startActivity(intent);
            }catch (Exception e){

            }


//            pdf.setVisibility(View.VISIBLE);
//            reportRefresh.setVisibility(View.GONE);
//            display(Environment.getExternalStorageDirectory() +
//                    "/temp",false);
//            show_pdf.setVisibility(View.VISIBLE);
        }

        @Override
        public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
            System.out.println("downloadProgress -- " + totalSize + "  " + currentSize + "  " + progress + "  " + networkSpeed);

//            String downloadLength = Formatter.formatFileSize(getApplicationContext(),
//                    currentSize);
//            String totalLength = Formatter.formatFileSize(getApplicationContext(), totalSize);
//            progres.setProgress((int) (currentSize/totalSize));
//            tvDownloadSize.setText(downloadLength + "/" + totalLength);
//            String netSpeed = Formatter.formatFileSize(getApplicationContext(), networkSpeed);
//            tvNetSpeed.setText(netSpeed + "/S");
//            tvProgress.setText((Math.round(progress * 10000) * 1.0f / 100) + "%");
        }

        @Override
        public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
            super.onError(isFromCache, call, response, e);
//            progres.setVisibility(View.GONE);
            closeProgressDialog();
            MAlert.alert("报告下载出错");
//            btnFileDownload.setText("下载出错");
        }
    }

}
